package com.server.dataSource;

import com.dao.chart.ChartsConfigMapper;
import com.dao.dataSource.DataConnectorMapper;
import com.dao.user.UserMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.model.bo.BaseToDataInfo;
import com.model.bo.ColumnConfigAndSql;
import com.model.bo.DatabaseConfig;
import com.model.bo.GroupUpdateId;
import com.model.po.BaseConfig;
import com.model.po.DataConnector;
import com.model.po.DataConnectorList;
import com.model.pojo.RepCode;
import com.model.pojo.RepEntity;
import com.model.pojo.TestPage;
import com.model.vo.configVo.ChangeOrderInfo;
import com.model.vo.configVo.ColumnRenameInfo;
import com.model.vo.configVo.DataConnectorInfo;
import com.model.vo.configVo.GroupInfo;
import com.model.vo.dataVo.ColumnValuesInfo;
import com.server.chart.GetChartsDataUtilService;
import com.server.strategy.StrategysService;
import com.server.chart.ChartsUtilService;
import com.config.BasesSource.DynamicDataSourceContextHolder;
import com.util.GetTokenData;
import com.util.ScreenUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class DataConnectorService {

    @Autowired
    private DataConnectorMapper dataConnectorMapper;

    @Autowired
    ObjectMapper objectmapper;

    @Autowired
    ScreenUtil screenUtil;
    @Autowired
    StrategysService strategysService;
    @Autowired
    GetTokenData getTokenData;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ChartsConfigMapper chartsConfigMapper;
    @Autowired
    ChartsUtilService chartsUtilService;
    @Autowired
    GetChartsDataUtilService getChartsDataUtilService;
    /*
    保存数据源
     */
    public RepEntity setDataConnector(String token, DataConnectorInfo dataConnectorInfo){

        Map<String, String> resultMap = getTokenData.getTokenData(token);
        int id = Integer.parseInt(resultMap.get("id"));
        String userName = resultMap.get("name");

        if (dataConnectorInfo == null || "".equals(dataConnectorInfo)){
            return new RepEntity(RepCode.Null);
        }
        DataConnector dataConnector = new DataConnector();
        BeanUtils.copyProperties(dataConnectorInfo,dataConnector);

        //取出数据库连接ID
        DatabaseConfig dbConfig = dataConnectorInfo.getDbConfig();
        int dbConId = dbConfig.getId();
        String pw = dataConnectorMapper.getBasesById(dbConId);
        dbConfig.setPassWord(pw);

//        String tableName = SqlMatch.matchSql(dataConnector.getLoadObject());
        dataConnector.setTableName(dataConnector.getLoadObject());

         String columnConfig = null;
         String databaseConfig = null;
         String dataTag = null;

        try {
            columnConfig = objectmapper.writeValueAsString(dataConnectorInfo.getColumnConfig());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        try {
            databaseConfig = objectmapper.writeValueAsString(dbConfig);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        try {
            dataTag = objectmapper.writeValueAsString(dataConnectorInfo.getDataTag());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        dataConnector.setColumnConfig(columnConfig);
        dataConnector.setDbConfig(databaseConfig);
        dataConnector.setDataTag(dataTag);
        if (dataConnector.getConnectorGroup() == 0){
            dataConnector.setConnectorGroup(-1);
        }

        if (dataConnectorInfo.getNote() == null || "".equals(dataConnectorInfo)){
            dataConnector.setNote("");
        }

        System.out.println(dataConnector);

        dataConnector.setCreateBy(userName);
        dataConnector.setCreateId(id);
        dataConnectorMapper.insertDataConnector(dataConnector);
        int dataId = dataConnector.getDataId();
        return new RepEntity(RepCode.success,dataId);
    }

    //查看数据源列表
    public RepEntity getListConnector(String token, TestPage testPage){
        Map<String, String> resultMap = getTokenData.getTokenData(token);
        String id = resultMap.get("id");
        System.out.println("id:" + id);
        List<DataConnectorList> listConnector = dataConnectorMapper.getDataConnectorList(Integer.parseInt(id), testPage.enablePaging());
        List<DataConnectorList> listConnectors = new ArrayList<>();
        Iterator isList = listConnector.iterator();
        while (isList.hasNext()){
            DataConnectorList dataConnectorList = (DataConnectorList) isList.next();
            System.out.println("ddddd:"+dataConnectorList);
            BaseConfig baseConfig = new BaseConfig();
            String dbConfig = dataConnectorList.getDbConfig();
            try {
                baseConfig = objectmapper.readValue(dbConfig, BaseConfig.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            baseConfig.setPassWord("");
            try{
                dbConfig = objectmapper.writeValueAsString(baseConfig);
            }catch (Exception e) {
                e.printStackTrace();
            }
            dataConnectorList.setDbConfig(dbConfig);
            listConnectors.add(dataConnectorList);
        }
        PageInfo<DataConnectorList> pageInfo = new PageInfo<>(listConnectors);

        return new RepEntity(RepCode.success, pageInfo);
    }

    /*
    查看单个数据源配置
     */
    public RepEntity getConnector(int id){
        DataConnector dataConnector = dataConnectorMapper.getOneData(id);
        if (dataConnector == null){
            return new RepEntity(RepCode.DataNonExistent);
        }
        BaseConfig baseConfig = new BaseConfig();
        String dbConfig = dataConnector.getDbConfig();
        try {
            baseConfig = objectmapper.readValue(dbConfig, BaseConfig.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        baseConfig.setPassWord("");
        try{
            dbConfig = objectmapper.writeValueAsString(baseConfig);
        }catch (Exception e) {
            e.printStackTrace();
        }
        dataConnector.setDbConfig(dbConfig);
        System.out.println(dataConnector);
        return new RepEntity(RepCode.success, dataConnector);
    }

    /*
    更新数据源配置
     */
    public RepEntity updateData(DataConnectorInfo dataConnectorInfo){

        if (dataConnectorInfo == null && "".equals(dataConnectorInfo)){
            return new RepEntity(RepCode.Null);
        }
        DataConnector dataConnector = new DataConnector();
        BeanUtils.copyProperties(dataConnectorInfo,dataConnector);
        //获取表名
//        String tableName = SqlMatch.matchSql(dataConnector.getLoadObject());
        dataConnector.setTableName(dataConnector.getLoadObject());

        List<ColumnRenameInfo> columnConfig = dataConnectorInfo.getColumnConfig();
//        DatabaseConfig dbConfig = dataConnectorInfo.getDbConfig();
        List<String> dataTag = dataConnectorInfo.getDataTag();


        String columnConfigJson = null;
        String dbConfigJson = null;
        String dataTagJson = null;

        if (!("".equals(columnConfig)) && columnConfig != null){
            try {
                columnConfigJson = objectmapper.writeValueAsString(columnConfig);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            dataConnector.setColumnConfig(columnConfigJson);
        }

        dataConnector.setDbConfig(dbConfigJson);
        if (dataTag != null){
            try {
                dataTagJson = objectmapper.writeValueAsString(dataTag);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            dataConnector.setDataTag(dataTagJson);
        }

        if (dataConnector.getConnectorGroup() == 0){
            dataConnector.setConnectorGroup(-1);
        }

        System.out.println(dataConnector);

        dataConnectorMapper.updateData(dataConnector);
        return new RepEntity(RepCode.success);
    }

    /*
    转交数据源
     */
    public RepEntity changeOrder(ChangeOrderInfo changeOrderInfo, String token){
        Map<String, String> resMap = getTokenData.getTokenData(token);
        int userId = Integer.parseInt(resMap.get("id"));
        String name = userMapper.getName(changeOrderInfo.getUserId());
        int createId = dataConnectorMapper.getCreateIdById(changeOrderInfo.getId());
        if (createId != userId){
            return new RepEntity(RepCode.NoAuthority);
        }
        dataConnectorMapper.updataOrder(name, changeOrderInfo.getUserId(), changeOrderInfo.getId());
        return new RepEntity(RepCode.success);
    }

    /*
    更新数据源分组
     */
    public RepEntity updateConfigGroup(GroupUpdateId groupUpdateId){
        int id = groupUpdateId.getId();
        int groupId = groupUpdateId.getGroupId();
        dataConnectorMapper.updateConfigGroup(id, groupId);
        return new RepEntity(RepCode.success);
    }

    /*
    删除数据源
     */

    public RepEntity delDataConnector(List<Integer> idList){
        Iterator isList = idList.iterator();
//        while (isList.hasNext()){
//            int id = (int) isList.next();
//            List<String> chartName = dataConnectorMapper.getChartsName(id);
//            if (chartName.size() != 0){
//                return new RepEntity(RepCode.hasChartsUsing, chartName);
//            }
//        }
        dataConnectorMapper.deleteData(idList);
        return new RepEntity(RepCode.success);
    }

    /*
    创建数据源分组
     */
    public RepEntity setDataConnectorGroup(GroupInfo groupInfo){
        if (groupInfo == null || "".equals(groupInfo)){
            return new RepEntity(RepCode.Null);
        }
        dataConnectorMapper.setConnectorGroup(groupInfo);
        int id = groupInfo.getId();
        return new RepEntity(RepCode.success, id);
    }

    /*
    更新数据源分组
     */
    public RepEntity updataDataConnectorGroup(GroupInfo groupInfo){
        dataConnectorMapper.updataConnectorGroup(groupInfo);
        return new RepEntity(RepCode.success);
    }

    /*
   批量更新数据源分组
    */
    public RepEntity updataConnectorGroups(List<GroupInfo> groupInfoList){
        Iterator isList = groupInfoList.iterator();
        GroupInfo groupInfo = new GroupInfo();
        while (isList.hasNext()){
            groupInfo = (GroupInfo) isList.next();
            dataConnectorMapper.updataConnectorGroup(groupInfo);
        }

        return new RepEntity(RepCode.success);
    }

    /*
    删除数据源分组
     */
    public RepEntity delDataConnectorGroup(List<Integer> idList){
        List<Integer> integerList = idList;
        Iterator isList = integerList.iterator();
        while (isList.hasNext()){
            int id = (int) isList.next();
            List<String> groupName = dataConnectorMapper.getFatherId(id);
            if (groupName.size() != 0){
                return new RepEntity(RepCode.hasGroupUsing);
            }
            List<String> chartName = dataConnectorMapper.getConName(id);
            if (chartName.size() != 0){
                return new RepEntity(RepCode.hasConUsing);
            }
        }
        dataConnectorMapper.delConnectorGroup(idList);
        return new RepEntity(RepCode.success);
    }

    /*
    查询数据源分组列表
     */
    public RepEntity getConnectorGroup(){
        return new RepEntity(RepCode.success, dataConnectorMapper.getConnectorGroup());
    }

    /*
    查询数据源数据
     */
    public RepEntity getConnectorData(String token, BaseToDataInfo baseToDataInfo){

        int dataId = baseToDataInfo.getId();
        int baseId = getChartsDataUtilService.getBaseIdByConnect(dataId);
        System.out.println("切换数据库"+baseId);

        Map<String, String> resultMap = getTokenData.getTokenData(token);
        int id = Integer.parseInt(resultMap.get("id"));
        int createId = dataConnectorMapper.getCreateIdById(dataId);
        ColumnValuesInfo columnValuesInfo = new ColumnValuesInfo();
        ColumnConfigAndSql columnConfigAndSql = chartsConfigMapper.getConfigAndSql(dataId);
        String sql = columnConfigAndSql.getSql();
        String columnConfig = columnConfigAndSql.getColumnConfig();
        columnValuesInfo.setColumnConfig(columnConfig);
        String sqls = chartsUtilService.columnNameUtil(id, dataId, sql, true, 0, createId);

            try {
                if (!DynamicDataSourceContextHolder.isContainsDataSource(String.valueOf(baseId))) {
                    //joinPoint.getSignature() ：获取连接点的方法签名对象
                    System.out.println("数据源 " + baseId + " 不存在使用默认的数据源 -> ");
                } else {
                    System.out.println("使用数据源：" + baseId);
                    DynamicDataSourceContextHolder.setDataSourceType(String.valueOf(baseId));
                }
                List<Map<String, Object>> val = new ArrayList<>();
                if (id == createId) {
                    val = dataConnectorMapper.getValues(sql, baseToDataInfo.getTestPage().enablePaging());
                } else {
                    if ("".equals(sqls)) {
                        return new RepEntity(RepCode.NoAuthority);
                    }
                    val = dataConnectorMapper.getValues(sql, baseToDataInfo.getTestPage().enablePaging());
                }

                PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(val);
                columnValuesInfo.setValues(pageInfo);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("异常");
                return new RepEntity(RepCode.erro);
            } finally {
                System.out.println("关闭数据源");
                DynamicDataSourceContextHolder.clearDataSourceType();
            }
        return new RepEntity(RepCode.success, columnValuesInfo);
    }

}
